<template>
  <transition name="herin-message-fade">
    <div
      v-if="visible"
      :class="['herin-message is-center is-closable', `herin-message-${type}`]"
      :style="positionStyle"
    >
      <p class="herin-message-content">{{ message }}</p>
      <i class="herin-message-closeBtn el-icon-close" @click="close" />
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      message: '',
      duration: 3000,
      type: 'warn',
      onClose: null,
      closed: false,
      verticalOffset: 60,
      timer: null
    };
  },

  computed: {
    positionStyle() {
      const ratio = window.ratio;
      return {
        top: `${this.verticalOffset * ratio}px`
      };
    }
  },

  watch: {
    closed(newVal) {
      if (newVal) {
        this.visible = false;
      }
    }
  },
  mounted() {
    this.startTimer();
  },

  methods: {
    close() {
      this.closed = true;
      if (typeof this.onClose === 'function') {
        this.onClose(this);
      }
    },

    startTimer() {
      this.timer = setTimeout(() => {
        if (!this.closed) {
          this.close();
        }
      }, this.duration);
    }
  }
};
</script>
<style lang="scss" scoped>
.herin-message {
  width: 25rem;
  height: 2.5rem;
  box-sizing: border-box;
  border: .0625rem solid;
  border-radius: .25rem;
  position: fixed;
  left: 50%;
  top: 1.25rem;
  margin-left: -12.5rem;
  // transform: translateX(-50%);
  transition: opacity 0.3s, transform 0.4s, top 0.4s;
  padding: .9375rem .9375rem .9375rem 1.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  z-index: 10000;
  user-select: none;
  &-success {
    border-color: rgba(42, 212, 154, 1);
    background-color: rgba(42, 212, 154, 0.6);
  }
  &-warn  {
    border-color: rgba(255, 187, 51, 1);
    background-color: rgba(255, 187, 51, 0.6);
  }
  &-error {
    border-color: rgba(255, 85, 119, 1);
    background-color: rgba(255, 85, 119, 0.6);
  }
  &-content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 75%;
    &-long{
      max-width: 95%;
    }
  }
  &-closeBtn {
    display: block;
    width: 2.5rem;
    height: 2.5rem;
    line-height: 2.5rem;
    text-align: center;
    position: absolute;
    // top: 50%;
    right: 0rem;
    // transform: translateY(-50%);
    cursor: pointer;
    color: #fff;
    font-size: 1rem;
  }
}
.herin-message-fade-enter-active,
.herin-message-fade-leave-active {
  transition: all 0.5s;
}
.herin-message-fade-enter,
.herin-message-fade-leave-to {
  transform: translateY(-60px);
  opacity: 0;
}
</style>
